<?php

namespace app\api\controller\project;

use think\Controller;
use think\Request;

class Project extends Controller
{
    public function __construct()
    {
        parent::__construct();

        $this->ProjectModel = model('project.Project');  //预约项目表
        $this->OrderModel = model('project.Order'); //预约订单表
        $this->UserModel = model('User.User'); //用户表
        $this->RecordModel = model('User.Record'); //消费表
        $this->AddressModel = model('User.Address'); //收货地址表
    }

    //订单列表
    public function index()
    {
        if ($this->request->isPost()) {
            $userid = $this->request->param('userid', 0);
            $status = $this->request->param('status', '');

            $user = $this->UserModel->find($userid);

            if (!$user) {
                $this->error('用户不存在');
                exit;
            }

            $where = [
                'userid' => $userid
            ];

            //不全等 0 !== ''
            if ($status !== '') {
                $where['status'] = $status;
            }

            $order = $this->OrderModel->with(['project'])->where($where)->order('createtime', 'desc')->select();

            $this->success('返回预约列表', null, $order);
            exit;
        }
    }

    //下订单
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->param();

            $userid = $this->request->param('userid', 0); //用户id
            $addrid = $this->request->param('addrid', 0); //收货地址id
            $projectid = $this->request->param('projectid', 0); //预约服务类型id
            $createtime = $this->request->param('createtime', 0); //预约时间 (单位:秒)

            //判断用户是否存在
            $user = $this->UserModel->find($userid);

            if (!$user) {
                $this->error('用户不存在');
                exit;
            }

            //判断收货地址存不存在
            $address = $this->AddressModel->find($addrid);

            if (!$address) {
                $this->error('收货地址不存在');
                exit;
            }

            //判断这个收货地址是不是这个用户的
            if ($address['userid'] != $userid) {
                $this->error('非法选择上门地址');
                exit;
            }

            //判断服务选项是否存在
            $project = $this->ProjectModel->find($projectid);

            if (!$project) {
                $this->error('预约的服务不存在，请重新选择');
                exit;
            }

            //将毫秒转化为秒
            $createtime = $createtime / 1000;

            //判断是否为过期时间
            $now = time() + 3600 * 6;

            if ($createtime < $now) {
                $this->error('请选择有效时间，在当前时间的6个小时后预约');
                exit;
            }

            //组装数据
            $data = [
                'userid' => $userid,
                'addrid' => $addrid,
                'projectid' => $projectid,
                'content' => $params['content'],
                'createtime' => $createtime,
                'status' => 0
            ];

            $result = $this->OrderModel->validate('common/Project/Order')->save($data);

            if ($result === FALSE) {
                $this->error($this->OrderModel->getError());
                exit;
            } else {
                $this->success('预约成功，请等待客服联系', '/pages/project/index');
                exit;
            }
        }
    }

    //订单详情
    public function info()
    {
        if ($this->request->isPost()) {
            $proid = $this->request->param('proid', 0);
            $userid = $this->request->param('userid', 0);

            $where = [
                'order.id' => $proid,
                'order.userid' => $userid
            ];

            //获取预约列表
            $order = $this->OrderModel->alias("order")->with(['project'])->where($where)->find();

            if (!$order) {
                $this->error('暂无预约记录');
                exit;
            } else {
                $this->success('返回预约记录', null, $order);
                exit;
            }
        }
    }

    //订单支付
    public function pay()
    {
        if ($this->request->isPost()) {
            $userid = $this->request->param('userid', 0);
            $proid = $this->request->param('proid', 0);

            //先获取预约记录
            $where = [
                'order.userid' => $userid,
                'order.id' => $proid
            ];

            $order = $this->OrderModel->alias('order')->with(['project'])->where($where)->find();

            if (!$order) {
                $this->error('预约记录不存在');
                exit;
            }

            //查询用户
            $user = $this->UserModel->find($userid);

            if (!$user) {
                $this->error('用户不存在');
                exit;
            }

            //用户积分
            $UserPoint = $user['point'];

            //预约记录积分
            $OrderPont = $order['price'];

            //计算
            $UpdatePoint = bcsub($UserPoint, $OrderPont);

            //判断用户的积分是否充足
            if ($UpdatePoint < 0) {
                $this->error('用户积分不足');
                exit;
            }

            //更新预约状态(已支付==2)  更新用户表的积分  插入一个消费记录表

            //开启事务
            $this->OrderModel->startTrans();
            $this->UserModel->startTrans();
            $this->RecordModel->startTrans();

            //更新预约状态
            $OrderData = [
                'id' => $proid,
                'status' => 2
            ];

            $OrderStatus = $this->OrderModel->isUpdate(true)->save($OrderData);

            if ($OrderStatus === FALSE) {
                $this->error($this->OrderModerl->getError());
                exit;
            }

            //更新用户积分状态
            $UserData = [
                'id' => $userid,
                'point' => $UpdatePoint
            ];

            $UserStatus = $this->UserModel->isUpdate(true)->save($UserData);

            if ($UserStatus === FALSE) {
                $this->OrderModel->rollback();
                $this->error($this->UserModel->getError());
                exit;
            }


            //插入消费记录
            $RecordData = [
                'point' => $OrderPont,
                'content' => "预约服务：" . $order['project']['name'] . "---消费的积分为：$OrderPont",
                'state' => 6,
                'userid' => $userid
            ];

            $RecordStatus = $this->RecordModel->validate('common/User/Record')->save($RecordData);

            if ($RecordStatus === FALSE) {
                $this->UserModel->rollback();
                $this->OrderModel->rollback();

                $this->error($this->RecordModel->getError());
                exit;
            }

            if ($OrderStatus === FALSE || $UserStatus === FALSE || $RecordStatus === FALSE) {
                $this->RecordModel->rollback();
                $this->UserModel->rollback();
                $this->OrderModel->rollback();
                $this->error('支付失败');
                exit;
            } else {
                $this->RecordModel->commit();
                $this->UserModel->commit();
                $this->OrderModel->commit();
                $this->success('支付成功，等待平台处理，安排上门服务');
                exit;
            }
        }
    }
}
